// pages/speechInput/speechInput.js
//智能输入档案页面
import test from '../../utils/test.js'
import {setAddress} from '../../utils/settings'
const app = getApp()
const plugin = requirePlugin("WechatSI")
const manager = plugin.getRecordRecognitionManager()
let backgroundAudioManager = wx.getBackgroundAudioManager()
const ages = []
//生成年龄数组，供picker选择
for (let i = 1; i <= 100; i++) {
  ages.push(i + "岁")
}
Component({
  data: {
    //用户基本信息，初始数据
    userdata:{
      userGender:0,
      userAge:0,
      userDisabilityType:0,
      userDisabilityCause:0,
      userDisabilityLevel:0,
      userBehaviorPhase:0,
    },
    userInfo:{},
    
    //可选择的基本信息
    allDataNum:[
      ["男","女",],
      ["请选择"],
      ["儿麻后遗症", "骨关节疾患", "畸形", "脊柱脊髓伤病", "截/缺肢", "截瘫", 
      "精神", "脑瘫", "偏瘫", "视力", "听力", "言语", "肢体", "智力", "周围神经损伤"],
      ["产伤", "创伤或意外伤害", "发育畸形", "感染", "骨关节病", "疾病", "脊髓灰质炎",
     "脊髓损伤", "交通事故", "脑性瘫痪", "脑血管疾病", "其他外伤", "先天性损伤或发育障碍", "原因不明", 
     "早产", "窒息", "中毒"],
      ["一级","二级","三级","四级"],
      ["初次","中期","末期"],
    ],
    allGender:["男","女",],
    allDisabilityType:["儿麻后遗症", "骨关节疾患", "畸形", "脊柱脊髓伤病", "截/缺肢", "截瘫",
      "精神", "脑瘫", "偏瘫", "视力", "听力", "言语", "肢体", "智力", "周围神经损伤"],
    allDisabilityCause:["产伤", "创伤或意外伤害", "发育畸形", "感染", "骨关节病", "疾病", "脊髓灰质炎",
     "脊髓损伤", "交通事故", "脑性瘫痪", "脑血管疾病", "其他外伤", "先天性损伤或发育障碍", "原因不明", 
     "早产", "窒息", "中毒"],
    allDisabilityLevel:["一级","二级","三级","四级"],
    allBehaviorPhase:["初次","中期","末期"],
    
    
    questions:["请问您的性别是?","您多少岁了？","请问您的残疾类型是什么？","请问您的残疾原因是什么?","您的残疾等级是几级？"],
    questiontype:["Gender","Age","DisabilityType","DisabilityCause","DisabilityLevel",],
    allAges: ages,
    totalScore: 0,
    //识别结果
    userAnswer: '',
    //问题次序
    questionPos: -1,
    //返回文字相同次数
    repeatTime: 0,
    //是否展示卡片
    showCard: false,
    showHintcard: false,
    //是否开始
    isBegin: false,
    //当前问题
    thisQuestion: '',
    thisAnswerList: [],
    //当前答案
    thisAnswer: '',
  },
  methods: {
    begin:function(){
      this.setData({
        questionPos: this.data.questionPos + 1,
        //showCard: true,
        isBegin: true
      })
      
    },
    closeCard(){
      this.setData({
        showCard: false
      })
    },
 
    addscore: function(){
      wx.navigateTo({
        url: '/pages/index/index',
      })
    },

    submitCard:function(){
      this.data.userInfo.record.gender = this.data.userdata.userGender
      this.data.userInfo.record.age = this.data.userdata.userAge
      this.data.userInfo.record.disabilityType = this.data.userdata.userDisabilityType
      this.data.userInfo.record.disabilityCause = this.data.userdata.userDisabilityCause
      this.data.userInfo.record.disabilityLevel = this.data.userdata.userDisabilityLevel
      this.data.userInfo.record.behaviorPhase = this.data.userdata.userBehaviorPhase
      wx.request({
        url: setAddress,
        data: this.data.userInfo,
        method: "POST",
        success:(res)=>{
          wx.setStorageSync("userInfo", this.data.userInfo)
          wx.setStorageSync('changed', 1)
          wx.navigateBack()   
        },
        fail:(err)=>{
          wx.showToast({
            title: '保存失败',
            icon: 'error'
          })
        }
      })
      
    },
    //文字转语音
    playsound:async function(con) {
      plugin.textToSpeech({
        lang: "zh_CN",
        tts: true,
        content: con,
        success: function(res) {
            console.log("succ tts", res.filename)  
            backgroundAudioManager.src = res.filename
            backgroundAudioManager.title = con
        },
        fail: function(res) {
            console.log("fail tts", res)
        }
      })
    },
  
    //录音功能
    streamRecord: function() {
      manager.start({
        lang: 'zh_CN',
      })
      this.setData({
        showHintcard: true
      })
    },
    streamRecordEnd:async function() {
      manager.stop()
      this.setData({
        showHintcard: false
      })
      let ans = await test(this.data.questiontype[this.data.questionPos], this.data.currentText)
      if (ans !== "no"){
        var changedType = 'userdata.user'+this.data.questiontype[this.data.questionPos]
        this.setData({
          thisAnswer: ans,
          [changedType]: ans,
          questionPos: this.data.questionPos + 1,
        })
        console.log(this.data.userdata)
      }else {
        wx.showToast({
          title: '请再说一遍',
          icon: 'error',
        })
      }

    },
    clickItem(e){
      var changedType = 'userdata.user'+this.data.questiontype[this.data.questionPos]
      var ans = e.target.dataset.choice
      this.setData({
        thisAnswer: ans,
        [changedType]: ans,
        questionPos: this.data.questionPos + 1
      })
      this.setData({
        showHintcard: false
      })
      console.log(e.target.dataset.choice)
    },
    nextQuestion(){
      this.setData({
        questionPos: this.data.questionPos + 1,
        showHintcard: false,
      })
    },
    //语音转文字
    initRecord: function() {
      //有新的识别内容返回，则会调用此事件
      manager.onRecognize = (res) => {
        let text = res.result
        console.log(text)
        this.setData({
          currentText: text,
        })
      }
      // 识别结束事件
      manager.onStop = (res) => {
        let text = res.result
        if(text == '') {
          // 用户没有说话，可以做一下提示处理...
          return
        }
        // 得到完整识别内容就可以去翻译了
        // this.translateTextAction()
      }
    },
    
  
    onLoad: function (options) {
      this.initRecord()
    },
  
    onShow: function () {
      this.data.userInfo = wx.getStorageSync("userInfo")
      let totalScore = 0
      for(let key in this.data.userInfo.score){
        totalScore += parseInt(this.data.userInfo.score[key])
      }
      this.setData({
        totalScore: totalScore,
        userInfo: wx.getStorageSync("userInfo"),
        'userdata.userBehaviorPhase': wx.getStorageSync("userInfo").record.behaviorPhase

      })
    },
    //绑定表单编辑
    bindNameInput(e){
      this.setData({
        'userInfo.name':e.detail.value
      })
    },
    bindGenderChange(e){
      this.setData({
        'userdata.userGender': this.data.allGender[e.detail.value]
      })
    },
    bindAgeChange(e){
      this.setData({
        'userdata.userAge': this.data.allAges[e.detail.value]
      })
    },
    bindDisabilityTypeChange(e){
      this.setData({
        'userdata.userDisabilityType': this.data.allDisabilityType[e.detail.value]
      })
    },
    bindDisabilityCauseChange(e){
      this.setData({
        'userdata.userDisabilityCause': this.data.allDisabilityCause[e.detail.value]
      })
    },
    bindDisabilityLevelChange(e){
      this.setData({
        'userdata.userDisabilityLevel': this.data.allDisabilityLevel[e.detail.value]
      })
    },
    bindBehaviorPhaseChange(e){
      this.setData({
        'userdata.userBehaviorPhase': this.data.allBehaviorPhase[e.detail.value]
      })
    },
    toLast(){
      this.setData({
        questionPos: this.data.questionPos - 1,
      })
    },
    toNext(){
      this.setData({
        questionPos: this.data.questionPos + 1,
      })
    },
  },
  observers:{
    "questionPos": function(questionPos){
      if(this.data.questionPos < this.data.questions.length){
        this.setData({
          thisQuestion: this.data.questions[questionPos],
          thisAnswerList: this.data.allDataNum[questionPos]
        })
        let answers = ""
        this.data.allDataNum[questionPos].forEach(element => {
          answers = answers + element +"，"
        });
        this.playsound(this.data.questions[questionPos])

      }else{
        this.setData({
          showCard: true
        })
      }
      

    }
  },

 
})